package top.mccat.raven.combatstatus.factory;

import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import top.mccat.raven.combatstatus.domain.CombatConfig;
import top.mccat.raven.combatstatus.utils.MsgUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author Distance
 * @date 2022/6/14
 */
public class ConfigFactory {
    private final YamlConfiguration yamlConfiguration = new YamlConfiguration();
    private final File configFile;
    private final JavaPlugin plugin;
    private final CommandSender commandSender;
    private MsgUtils msgUtils;

    public ConfigFactory(JavaPlugin plugin, MsgUtils msgUtils) {
        this.plugin = plugin;
        this.msgUtils = msgUtils;
        if(msgUtils == null){
            this.msgUtils = new MsgUtils(null);
        }
        commandSender = plugin.getServer().getConsoleSender();
        File dataFolder = plugin.getDataFolder();
        configFile = new File(dataFolder,"config.yml");
    }

    private void loadConfig(){
        try {
            msgUtils.sendToConsole(commandSender,"==>&a正在加载插件配置文件...");
            yamlConfiguration.load(configFile);
            msgUtils.sendToConsole(commandSender,"==>&c插件配置文件加载成功！");
        } catch (IOException | InvalidConfigurationException e) {
            msgUtils.sendToConsole(commandSender,"==>&c错误，配置文件不存在，正在重新生成配置文件中...");
            plugin.saveResource("config.yml",false);
            msgUtils.sendToConsole(commandSender,"==>&b配置文件生成成功，正在重新读取插件配置文件...");
        }
    }

    public CombatConfig readCombatConfig(){
        loadConfig();
        ConfigurationSection combaStatus = yamlConfiguration.getConfigurationSection("combatstatus");
        if(combaStatus==null){
            msgUtils.sendToConsole(commandSender,"==>配置文件中的 combatstatus 参数不存在，请检查配置文件参数！");
            return null;
        }
        String pluginName = combaStatus.getString("pluginName");
        int time = combaStatus.getInt("time");
        String fightMsg = combaStatus.getString("fightMsg");
        String leaveMsg = combaStatus.getString("leaveMsg");
        return new CombatConfig(pluginName,time,fightMsg,leaveMsg);
    }

    /**
     * 作者信息menu
     */
    public void authorMenu(){
        msgUtils.sendToConsole(commandSender,"&4&l===----------&6&l[CombatStatus]&4&l-----------===");
        msgUtils.sendToConsole(commandSender,"&b             制作者： Raven       ");
        msgUtils.sendToConsole(commandSender,"&b             QQ ： 740585947     ");
        msgUtils.sendToConsole(commandSender,"&b  如有bug可以在bbs论坛下留言反馈，蟹蟹！");
        msgUtils.sendToConsole(commandSender,"&4&l===----------&6&l[CombatStatus]&4&l-----------===");
    }

    public void setMsgUtils(MsgUtils msgUtils) {
        this.msgUtils = msgUtils;
    }
}
